﻿#ifndef MEMORYCHUNK_H
#define MEMORYCHUNK_H

#include <stdint.h>
#include "semaphore.h"

namespace RemoteObj
{
class MemoryChunk;
struct BlockHeader
{
    MemoryChunk* chunk;
    int32_t len;
};

struct MemoryBlock;

struct BlockData
{
    union
    {
        MemoryBlock* next;
        int8_t buffer;
    };
};
struct MemoryBlock
{
    BlockHeader header;
    BlockData data;
};

class MemoryChunk
{
public:
    MemoryChunk(int32_t size, int32_t count);
    ~MemoryChunk();
    void* malloc();
    static void free(void* mem);
    MemoryChunk* next()
    {
        return _next;
    }
protected:
    MemoryBlock* create_block();
    void free(MemoryBlock* Block);
    void delete_block(MemoryBlock* block);
private:
    MemoryBlock* _freelist;
    int32_t _size;
    int32_t _count;
    MemoryChunk* _next;
    Semaphore _sem;
};
}

#endif // MEMORYCHUNK_H
